package com.example.cardgame

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.gridlayout.widget.GridLayout
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import cn.edu.sicnu.cardgame.CardMatchingGame
import com.example.cardgame.ui.theme.CardGameTheme

class MainActivity : ComponentActivity(),View.OnClickListener {
    lateinit var game: CardMatchingGame
    var highestScore = 0
    val cardButtons = mutableListOf<Button>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        enableEdgeToEdge()
        val gridLayout = findViewById<GridLayout>(R.id.gridlayout)

        for (i in 0 until gridLayout.childCount) {
            val v = gridLayout.getChildAt(i)
            if(v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        val button1 = findViewById<Button>(R.id.button1)
        val button2 = findViewById<Button>(R.id.button2)
        button1.setOnClickListener {
            val intent = Intent()
            intent.putExtra("highestScore", highestScore)
            setResult(RESULT_OK, intent)
            finish()
        }
        button2.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }

    }
    fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.card)
            }
        }
        val score = findViewById<TextView>(R.id.textView)
        score.text = String.format("得分: %d", game.score)
        if (game.score > highestScore) {
            highestScore = game.score
        }
    }

    override fun onClick(v: View?) {
        if(v !is Button) return
        val index = cardButtons.indexOf(v)
        game.chooseCardAtIndex(index)
        updateUI()
    }
}
